<?php namespace app\common\controller;

class Token{
	
	private $cacheServiceObj = '';
	
	public function __construct(){
		if(empty($this -> cacheServiceObj)) $this -> cacheServiceObj = controller("service/Cache");
	}
	
    /**
     * 生成用户TOKEN
     * @param int $id 传来的用户ID
     * @param int $userInfo['loginType'] 登录类型
     * @param int $userType 用户类型
     * @return hash 加密后的哈希字串
     * @return $password 用户加密后密码
     * @access public
     */
    public function setToken($userInfo = null, $userType = 1){
    	if(is_null($userInfo)) return false;
		
//		雪花算法生成不重复的随机数值串（有负数，可反解析）
		$str = controller("common/SnowFlake") -> make($userInfo);
		$token = md5($str);
		
//		到期时间
        $expireTime = isset( $userInfo['loginTime'] ) ? $userInfo['loginTime'] : $this -> createExpireTime();
		
//		设置用户登陆缓存
		$setTokenRe = $this -> setLoginCache($userInfo, $token, $expireTime, $userType);
		
        return $setTokenRe ? $token : $setTokenRe;
    }
    
	/**
	 * 获取登陆缓存到期时间戳(秒)
	 * @return	intval	到期时间戳
	 */
	private function createExpireTime(){
		return $_SERVER['REQUEST_TIME'] + config('LOGIN_EXPIRE_TIME');
	}
	
	/**
	 * 设置登陆缓存
	 * @param	array		$userInfo		用户信息	
	 * @param	string		$token			登陆token	
	 * @param	string|int	$expireTime		过期时间	
	 * @return	true|false
	 */
	private function setLoginCache($userInfo, $token, $expireTime, $userType){
		if(empty($userInfo) || empty($token) || empty($expireTime) || empty($userInfo['loginType'])) return FALSE;
		
		switch ($userInfo['loginType']) {
			case 1: $userInfo['loginType'] = 'Api'; break;	//接口
			case 2: $userInfo['loginType'] = 'WechatMinApi'; break;	//接口
			case 3: $userInfo['loginType'] = 'WechatMinApi'; break;	//接口
			case 4: $userInfo['loginType'] = 'WechatMinApi'; break;	//接口
			case 5: $userInfo['loginType'] = 'WechatMinApi'; break;	//接口
			case 6: $userInfo['loginType'] = 'WechatMinApi'; break;	//接口
			default: return FALSE; break;
		}
		
		$cacheServiceObj = controller("service/Cache");
		
		switch ($userType) {
			case 1: $userCacheName = 'userToken'; break;
			case 2: $userCacheName = 'userToken'; break;
			case 3: $userCacheName = 'userToken'; break;
			case 4: $userCacheName = 'userToken'; break;
			case 5: $userCacheName = 'userToken'; break;
			case 6: $userCacheName = 'userToken'; break;
			case 7: $userCacheName = 'userToken'; break;
			default: $userCacheName = 'userToken'; break;
		}
		
//		所有用户缓存
		$userCacheAll = $cacheServiceObj -> getCache($userCacheName, '');
		if(config('SINGLE_LOGIN')){
//			已开启单点登陆
			$newCache = $this -> setSingleLoginCacheData($userCacheAll, $userInfo, $token, $expireTime);
		}else{
//			未开启单点登陆
			$newCache = $this -> setloginCacheData($userCacheAll, $userInfo, $token, $expireTime);
		}
		
		$userRe = $cacheServiceObj -> setCache($userCacheName, '', $newCache['user']);
		
		return ($userRe) ? TRUE : FALSE;
	}
	
	/*
	 * 重组单点登陆数据
	 */
	private function setSingleLoginCacheData($userCacheAll, $userInfo, $token, $expireTime){
		$userId = $userInfo['id'];
		$sysId = isset($userInfo['sysId']) ? $userInfo['sysId'] : 0;
		$pwd = $userInfo['pwd'];
		$loginType = $userInfo['loginType'];
		$userCache = isset($userCacheAll['user_' . $userId]) ? $userCacheAll['user_' . $userId] : [];
		
//		用户缓存
		$userCache['userId'] = $userId;
		$userCache['sysId'] = $sysId;
		$userCache['pwd'] = $pwd;
		$userCache['expireTime'] = $expireTime;
		$userCache['loginToken'][$loginType] = [
			$token => [
				'setTokenTime' => time(),				//设置token时间戳
				'tokenExpireTime' => $expireTime,		//token有效期(秒)
			]
		];
		
		$userCacheAll['user_' . $userId] = $userCache;
		
		$newToken['user'] = $userCacheAll;				//重组后所有用户缓存数据
		return $newToken;
	}
	
	/**
	 * 重组多点登陆数据
	 */
	private function setloginCacheData($userCacheAll, $userInfo, $token, $expireTime){
		$userId = $userInfo['id'];
		$sysId = isset($userInfo['sysId']) ? $userInfo['sysId'] : 0;
		$pwd = $userInfo['pwd'];
		$loginType = $userInfo['loginType'];
		$userCache = isset($userCacheAll['user_' . $userId]) ? $userCacheAll['user_' . $userId] : '';
//		用户缓存
		if(is_null($userCache) || empty($userCache)){
			$userCache = [
				'userId' => $userId,
				'sysId' => isset($userInfo['sysId']) ? $userInfo['sysId'] : 0,
				'pwd' => $pwd,
				'expireTime' => $expireTime,
//				'loginToken'[$loginType] => [$token => $expireTime],
			];
			$userCache['loginToken'][$loginType][$token] = [
				'setTokenTime' => time(),				//设置token时间戳
				'tokenExpireTime' => $expireTime,		//token有效期(秒)
			];
		}else{
			$userCache['userId'] = $userId;
			$userCache['sysId'] = isset($userInfo['sysId']) ? $userInfo['sysId'] : 0;
			$userCache['pwd'] = $pwd;
			$userCache['expireTime'] = $expireTime;
			$userCache['pwd'] = $pwd;
			$userCache['loginToken'][$loginType][$token] = [
				'setTokenTime' => time(),				//设置token时间戳
				'tokenExpireTime' => $expireTime,		//token有效期(秒)
			];
		}
		$userCacheAll['user_' . $userId] = $userCache;
		
		
		$newToken['user'] = $userCacheAll;		//重组后所有用户缓存数据
		return $newToken;
	}
    
}
